const express = require("express");
// 有什么难的，express, mysql, sequelize, zpqy, sequelize-cli 所有技术都只是我的工具而已，怕什么？
const { Category, Course } = require("../../models");
const { Op } = require("sequelize");
const { success, fail } = require("../../utils/response");
const {NotFound, BadRequest, Conflict} = require('http-errors')
/**
 * 分类路由-管理后台
 * 1.分页查询 支持keywords查询
 * 2.查询所有，暂不需要
 * 3.分类详情
 * 4.增加分类
 * 5.删除分类
 * 6.修改分类
 */
const router = express.Router();
// 查询分类-带分页
router.get("/", async (req, res) => {
  try {
    const { pageNum, pageSize } = req.query;
    const conditions = getConditions(req);
    const { count, rows } = await Category.findAndCountAll(conditions);
    success(res, "获取成功", {
      pageNum,
      pageSize,
      count,
      list: rows,
    });
  } catch (error) {
    // console.log("自主抛出的错误！", error.name);
    fail(res, error);
  }
});
// 获取参数
function getConditions(req) {
  const { keywords, pageNum, pageSize } = req.query;
  const conditions = {
    where: {},
    // attributes: ["id", "name", "rank"],
  };
  // 分页参数，没传分页 就是查询所有
  const page = Math.abs(pageNum);
  const size = Math.abs(pageSize);
  if (page && size) {
    conditions.offset = (page - 1) * size;
    conditions.limit = size;
  }
  // 处理普通参数
  if (keywords) {
    conditions.where.name = {
      [Op.like]: `%${keywords}%`,
    };
  }
  return conditions;
}
// 查询分类-无分页
router.get("/all", async (req, res) => {
  try {
    const { keywords } = req.query;
    let where = {};

    if (keywords) {
      where.name = {
        [Op.like]: `%${keywords}%`,
      };
    }
    const raws = await Category.findAll({ where });
    success(res, "获取成功", raws);
  } catch (error) {
    fail(res, error);
  }
});
// 查询分类详情
router.get("/:id", async (req, res) => {
  try {
    const { id } = req.params;
    if(!id) {
      throw BadRequest('分类id不能为空')
    }
    const conditions = {
      include: {
        model: Course,
        as: 'courses',
        attributes: ['id', 'name', 'imgUrl', 'introduce', 'rank', 'createdAt', 'likeCount']
      }
    }
    const category = await Category.findByPk(id,conditions);
    if (!category) {
      throw NotFound("未找到此分类");
    }
    success(res, "获取成功", category);
  } catch (error) {
    fail(res, error);
  }
});
// 增加分类
router.post("/", async (req, res) => {
  try {
    const param = filterParamByWhiteName(req);
    const category = await Category.create(param);
    success(res, "success", category);
  } catch (error) {
    fail(res, error);
  }
});
// 修改分类
router.put("/:id", async (req, res) => {
  try {
    const { id } = req.params;
    if(!id) {
      throw BadRequest('分类id不能为空')
    }
    const param = filterParamByWhiteName(req);
    const category = await Category.update(param, {
      where: {
        id,
      },
    });
    if (!category) {
      throw NotFound("未找到此分类");
    }
    success(res, "success", category);
  } catch (error) {
    fail(res, error);
  }
});
// 删除分类
router.delete("/:id", async (req, res) => {
  try {
    const { id } = req.params;
    const conditions = {
      where: {
        CategoryId: id
      }
    }
    const couseCount = await Course.count(conditions)
    if(couseCount > 0) {
      throw new Conflict('该分类下有课程，暂不能删除')
    }
    const category = await Category.destroy({
      where: { id },
    });
    if (!category) {
      throw NotFound("未找到此分类");
    }
    success(res, "success");
  } catch (error) {
    fail(res, error);
  }
});
// 拿到需要的请求参数 - 用于新增、编辑、查询条件
function filterParamByWhiteName(req) {
  const { name, rank } = req.body;
  const data = {}
  if(name) {
    data['name'] = name
  }
  if(rank) {
    data['rank'] = rank
  }
  return data;
}

module.exports = router;
